package cn.edu.nju.software.servlet.user;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Hashtable;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.edu.nju.software.model.user.Store;
import cn.edu.nju.software.model.user.UserLoginVerifier;

/**
 * Servlet implementation class UserLoginServlet
 */
public class UserLoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		PrintWriter writer = response.getWriter();

		request.setCharacterEncoding("UTF-8");
		
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		UserLoginVerifier verifier = new UserLoginVerifier();
		if (verifier.verify(username, password)) {
			getServletContext().setAttribute("username", username);
			getServletContext().setAttribute("store", new Hashtable<Integer, Integer>());
			Store.setServletContext(getServletContext());
			
			response.sendRedirect("/cineplex/user/home.jsp");
			return;
		} else {
			writer.println("<script>alert('Error! Please check the username and password');"
					+ "window.location.href='index.jsp';</script>");
		}
	}

}
